import { ErrorInfo } from '@src/api/OnError';

/**
 * 异常监控-外部监控
 * 使用方法:window.onerror = *
 **/
export function onerror(msg, url, line) {
  // eslint-disable-next-line new-cap
  ErrorInfo({
    errorDec: msg,
    url,
    line
  });
}
/**
 * 异常监控-console
 * 使用方法:console.error = *
 **/

export function consoleError(msg, from) {
  let errorMsg = (arguments[0] && arguments[0].message) || msg;
  let url = (arguments[0] && arguments[0].config && arguments[0].config.url)
    || 'console.error';
  // eslint-disable-next-line new-cap
  if (!from) ErrorInfo({ errorDec: errorMsg, url });
  return window.oldError.apply(console, [arguments[0]]);
}
/**
 * 异常监控-无Promise的reject
 * 使用方法:window.onunhandledrejection = *
 * 备注：如果遇到接口404等情况。会造成循环，慎用
 **/
export function onUnhandledRejection(e) {
  let errorMsg = '';
  // eslint-disable-next-line no-unused-vars
  let errorStack = '';
  if (typeof e.reason === 'object') {
    errorMsg = e.reason.message;
    errorStack = e.reason.stack;
  } else {
    errorMsg = e.reason;
    errorStack = '';
  }
  // 处理上报
  onerror(errorMsg, 'onUnhandledRejection', 0);
}

/**
 * 异常监控-vue内部监控
 * 使用方法:vue.config.errorHandler = *
 **/
export function errorHandler(msg, component, life) {
  const params = {};
  if (msg) {
    params.errorDec = msg.toString();
  }
  if (component) {
    const dom = component.$vnode.tag.split('-');
    const arr = dom.slice(3, dom.length);
    if (arr.length > 1) params.module = arr.join('-');
    else params.module = arr[0];
  }

  if (life) {
    const lifes = life.split(' ');
    params.hook = lifes[0];
  }
  // eslint-disable-next-line new-cap
  ErrorInfo(params);
  consoleError(msg, 'vue');
}
export function production() {
  let url = window.location.host;
  const production = [
    'app.shb.ltd', // 正式环境下监控
    'shb3144.eapps.dingtalkcloud.com', // 正式环境下监控
    'cloud.shb.ltd' // 正式环境下监控
  ];
  return production.indexOf(url) > -1;
}

export async function asyncErrorCaptured (fn, rest = []) {
  try {
    let res = await fn(...rest)
    return [null, res]
  } catch (err) {
    console.log(err)
    return [err, null]
  }
}